package com.lemon.cloud.gateway.rule;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.cloud.nacos.balancer.NacosBalancer;
import com.lemon.cloud.comm.constants.GrayConstant;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author huangds
 * <p>
 * 基于客户端版本号灰度路由
 */
@Slf4j
@AllArgsConstructor
@Component
public class VersionGrayLoadBalancer implements GrayLoadBalancer {

    private DiscoveryClient discoveryClient;

    /**
     * 根据serviceId 筛选可用服务
     * @param serviceId 服务ID
     * @param request 当前请求
     * @return
     */
    @Override
    public ServiceInstance choose(String serviceId, ServerHttpRequest request) {
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);

        // 注册中心无实例 抛出异常
        if (CollUtil.isEmpty(instances)) {
            log.warn("No instance available for {}", serviceId);
            throw new NotFoundException("No instance available for " + serviceId);
        }

        // 获取请求version，无则权重返回可用实例
        String grayFlag = request.getHeaders().getFirst(GrayConstant.GRAY_FLAG);
        if (StrUtil.isBlank(grayFlag)) {
            //应该按照nacos 配置的
            return defaultServiceInstance(serviceId,grayFlag,instances);
        }

        // 遍历可以实例元数据，若匹配则返回此实例
        for (ServiceInstance instance : instances) {
            Map<String, String> metadata = instance.getMetadata();
            String targetVersion = MapUtil.getStr(metadata, GrayConstant.GRAY_FLAG);
            if (StrUtil.isNotEmpty(grayFlag)&&
                    grayFlag.equalsIgnoreCase(targetVersion)) {
                log.debug("gray requst match success :{} {}", grayFlag, instance);
                return instance;
            }
        }
        return defaultServiceInstance(serviceId,grayFlag,instances);
    }

    /**
     * 调用nacos官方提供的负载均衡权重算法
     * @param serviceId
     * @return
     */
    private ServiceInstance defaultServiceInstance(String serviceId,String grayFlag,List<ServiceInstance> instances){
        if (StrUtil.isEmpty(grayFlag)){
            List<ServiceInstance> oldInstance = instances.stream().filter(i -> StrUtil.isEmpty(i.getMetadata().get(GrayConstant.GRAY_FLAG))).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(oldInstance)){
                return NacosBalancer.getHostByRandomWeight3(oldInstance);
            }
        }
        return NacosBalancer.getHostByRandomWeight3(instances);
    }
}
